package cn.com.dstz.admin.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import cn.com.dstz.agent.config.AgentConfig;
import cn.com.dstz.agent.config.TradeConfig;
import cn.com.dstz.base.action.BaseAction;
import cn.com.dstz.data.post.IP_PropertiesLoad;
import cn.com.dstz.data.post.Post;
import cn.com.dstz.data.post.PostTask;
import cn.com.dstz.data.post.TradeKeyVal;
import cn.com.dstz.utils.ActionUtils;
import cn.com.dstz.utils.DataBaseUtils;
import cn.com.dstz.utils.DateUtils;
import cn.com.dstz.utils.FillNameQuery;
import cn.com.dstz.utils.PinYinUtils;
import cn.com.dstz.utils.ValidUtils;
import cn.com.dstz.web.constants.Constants;

/**
 * 开仓喊单管理
 * 二次修复: 
 * @author 叶装装
 * ‎2013/‎6/‎4  20:42 
 *
 */
public class TradeAct extends BaseAction{
	
	private void list( int status ){
		String sql = "select d.*, a.username, c.name from dstztrade d, dstzadmin a, dstzcategory c where d.status=" + status + " and d.category = c.id and d.adminid = a.id";
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		int level = ActionUtils.getAdminLevel( admin );
		
		Map< String, Object > valueMap = null;
		
		if( level > 0 ){
			String _config = AgentConfig.CONFIG_TRADE_OPEN;
			if( status == 2 ){
				_config = AgentConfig.CONFIG_TRADE_CLOSE;
			}
			
			TradeConfig config = new TradeConfig( admin, this.countManagerGroup( ),  _config  );
			sql += config.getSQL( );
			valueMap = config.getValueMap( );
		}
		
		this.responseToJsonObject( this.paginationBySQL( sql, null, valueMap,  null )  );
	}
	
	public void listclosetrade( ){
		list( 2 );
	}
	
	public void list( ){
		
		list( 1 );
		
	}
	
	public void add( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 0 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		String currentTime = DateUtils.getCurrentTime( );
		
		int save = baseService.save( "dstztrade", DataBaseUtils.getData( new String[]{
				"aid", "adminid", "usertype", "category", "direction", "openposition", "stopposition", "longposition",
				"starttime", "status", "reason"
		}, new Object[]{
				admin.get( "topaid" ), admin.get( "id" ), usertype, getCategoryId( ), direction, openposition, stopposition, longposition,
				currentTime, 1,  reason
		} ) );
		
		// 发送数据
		this.postData( this.getOpenTradeData( admin, currentTime ) );
		
		this.addLog( save, "trade", 0, admin.get( "id" ) + "开仓" );
		this.ajaxResponse( save > 0 ? 0 : -1 );
	}
	
	public void edit( ){
		
		int validSaveOrUpdate = validSaveOrUpdate( 1 );
		
		if( validSaveOrUpdate > 0 ){
			this.ajaxResponse( validSaveOrUpdate );
			return;
		}
		
		int update = baseService.update( "dstztrade", DataBaseUtils.getData( new String[]{
				"usertype", "category", "direction", "openposition", "stopposition", "longposition",
				 "reason"
		}, new Object[]{
				usertype, categoryId, direction, openposition, stopposition, longposition,
				 reason
		} ),
		DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} )
		);
		
		this.addLog( update, "trade", 1, "ID：" + id );
		this.ajaxResponse( update > 0 ? 0 : -1 );
		
	}
	
	public void delete( ){
		
		String ids = getParameter( "ids" );
		
		if( ids != null ){
			String [] splitIds = StringUtils.split( ids, "," );
			
			if( splitIds != null && splitIds.length > 0 ){
				List< String > updateSqlList = new ArrayList< String >( );
				
				Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
				int level = ActionUtils.getAdminLevel( admin );
				
				for( String id : splitIds ){
					if( StringUtils.isNotBlank( id )){
						String deleteSql = "delete from dstztrade where id =" + id;
						if( level > 0 ){
							deleteSql += " and adminid = " + admin.get( "id" );
						}
						
						updateSqlList.add( deleteSql );
					}
				}
				
				int del = baseService.saveOrUpdateBatch( updateSqlList );
				
				this.addLog( del, "trade", 2, ids );
			}
		}
		
	}
	
	public String toadd( ){
		setGroupList( );
		return "add";
	}
	
	// 转到编辑页面
	public String toedit( ){
		setGroupList( );
		int validSaveOrUpdate = validSaveOrUpdate( 2 );
		
		if( validSaveOrUpdate > 0 ){
			alertMsg( null );
			return "edit";
		}
		String sql = "select t.*, c.name from dstztrade t, dstzcategory c  where t.category = c.id and t.id=:id ";
		
		Map< String, Object > data = baseService.queryForMap( sql, FillNameQuery.fillValue( sql, id ) );
		
		if( data == null || data.isEmpty( ) ){
			alertMsg( null );
			return "edit";
		}
		
		getRequest( ).setAttribute( "data", data );
		
		
		return "edit";
	}
	
	public void closetrade( ){
		
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		//closeposition
		String sql = "select t.*, c.name from dstztrade t, dstzcategory c  where t.category = c.id and t.id=:id ";
		
		Map< String, Object > data = baseService.queryForMap( sql, FillNameQuery.fillValue( sql, id ) );
		
		if( data == null ){
			this.ajaxResponse( -1 );
			return;
		}
		
		// 空单2， 多单1
		// 空单 建仓价 - 平仓价   多单  平仓价-建仓价
		
		Short direction = ( Short )data.get( "direction" );
		
		float profit = 0f;
		Float openposition = ( Float ) data.get( "openposition" );
		
		if(  direction == 1 ){
			profit = closeposition - openposition;
		}else{
			profit = openposition - closeposition;
		}
		
		//String endtime = DateUtils.getCurrentTime( );
		
		String endtime = getParameterByDecode( "endtime" );

		String starttime = getParameterByDecode( "starttime" );
		String type = getParameter( "type" );
		if( StringUtils.isBlank( endtime )){
			endtime = DateUtils.getCurrentTime( );
		}
		
		if( StringUtils.isBlank( starttime )){
			starttime = ( String ) data.get( "starttime" );
		}
		
		int update = baseService.update( "dstztrade", DataBaseUtils.getData( new String[]{
				"direction", "openposition", "stopposition", "longposition", "closeposition",
				 "reason", "status", "endtime", "profit", "starttime"
		}, new Object[]{
				direction, openposition, stopposition, longposition, closeposition, 
				 reason, 2, endtime, profit, starttime
				 
		} ),
		DataBaseUtils.getData( new String[]{
				"id"
		}, new Object[]{
				id
		} )
		);
		
		if( update > 0 && StringUtils.isBlank( type ) ){
			this.postData( this.getCloseTradeData( admin, data, endtime, profit ) );
		}
		
		this.addLog( update, "trade", 1, "ID：" + id, "平仓" );
		this.ajaxResponse( update > 0 ? 0 : -1 );
		
	}
	
	public String toclosetrade( ){
		toedit( );
		return "closetrade";
	}
	
	public String toeditclosetrade( ){
		getRequest( ).setAttribute( "type", 1 );
		return toclosetrade( );
	}

	
	private int validSaveOrUpdate( int saveOrUpdate ){
		
		// 编辑或者删除
		if( saveOrUpdate == 2 || saveOrUpdate == 1 ){
			if( this.id == null || this.id == 0 ){
				return saveOrUpdate;
			}
			// 
			if( saveOrUpdate == 2 ){
				return 0;
			}
		}
		
		if( ValidUtils.validLength( categoryname, 1, 40 )){
			return 1;
		}
		
		initCategory( );
		
		if( this.categoryId == null || this.categoryId == 0 ){
			return 6; // 提示请选择喊单品种
		}
		
		return 0;
		
	}
	
	private void postData(Map< String, Object > postData ){
		if( postData == null ){
			return;
		}
		Post post = new Post( IP_PropertiesLoad.getInstance( ).getIps( ), new TradeKeyVal( postData ));
		postTask.addTask( post );
	}
	
	private Map< String, Object > getCloseTradeData( Map< String, Object > admin, Map< String, Object > data, String endtime, float profit ){
		Map< String, Object > postData =DataBaseUtils.getData( new String[]{
				"key", "topaid", "usertype", "name", "direction", "openposition",
				"stopposition", "longposition", "closeposition", "profit", "starttime",
				"endtime", "reason", "adminname"
		}, new Object[]{
				"pingcang", admin.get( "topaid" ), data.get( "usertype" ), data.get( "name" ),
				data.get( "direction" ), data.get( "openposition" ), data.get( "stopposition" ), data.get( "longposition" ), 
				closeposition, profit, data.get( "starttime" ), endtime, ( StringUtils.isBlank( reason ) ? "" : reason),
				 admin.get( "name" ) == null ? "" : admin.get( "name" )
		} );
		return postData;
	}
	
	private Map< String, Object > getOpenTradeData( Map< String, Object > admin, String starttime ){
		
		String sql = "select * from dstzcategory where id =:id";
		Map< String, Object > category = baseService.queryForMap( sql, FillNameQuery.fillValue( sql, categoryId ) );
		
		if( category == null || category.isEmpty( ) ){
			return null;
		}
		
		Map< String, Object > postData = DataBaseUtils.getData( new String[]{
				"key", "topaid", "usertype", "name", "direction", "openposition",
				"stopposition", "longposition", "closeposition", "profit", "starttime",
				"endtime", "reason", "adminname"
		}, new Object[]{
				"xiadan", admin.get( "topaid" ), usertype, category.get( "name" ),
				direction, openposition,stopposition, longposition, "", "", starttime, "", ( StringUtils.isBlank( reason ) ? "" : reason),
				 admin.get( "name" ) == null ? "" : admin.get( "name" )
		} );
		
		return postData;
	}
	
	private void setGroupList( ){
		
		Map< String, Object > valueMap = new HashMap< String, Object >( );
		valueMap.put( "ismanager", 0 );
		valueMap.put( "allowread", 1 );
		String sql = "select * from dstzgroup g, dstz_group_type t where g.id = t.groupid and t.ismanager=:ismanager and allowread=:allowread";
		
		List< Map< String, Object >> groupList = baseService.queryForListByAll( sql, valueMap );
		
		getRequest( ).setAttribute( "groupList", groupList );
		
	}
	
	/**
	 * 要处理品种的可能会造成null的问题
	 */
	private void initCategory( ){
		Map< String, Object > admin = this.getEntityInSession( Constants.ADMIN_IN_SESSION );
		//String sql = "select * from dstzcategory where `name`='"+categoryname+"'and adminid="+admin.get("id");
		String sql = "select id from dstzcategory where name=:name and adminid=:id";
		
		///Map< String, Object > valueMap = new HashMap< String, Object >( );
		Map< String, Object > category = baseService.queryForMap(sql, FillNameQuery.fillValue( sql, categoryname, admin.get( "id" ) ));
		if( category != null && !category.isEmpty( ) ){
			this.categoryId = ( Integer ) category.get( "id" ); // 查询
		}else{
			// 保存
			int save = baseService.save( "dstzcategory", DataBaseUtils.getData( new String[]{
					"name", "aid", "pinyin", "adminid"
			}, new Object[]{
					categoryname, admin.get( "topaid" ), PinYinUtils.getPinYinWithOutDuoyin( categoryname ), admin.get( "id" )
			} ), true );
			// 如果保存失败，品种id将是null
			// 已找到为null的原因，是转到编辑页面，进入valid方法时保存了一个
			if( save > 0 ){
				this.categoryId = save;
			}
		}
	}
	
	private Integer id;
	
	private String usertype;
	private Integer categoryId;
	private Short direction;
	private Float openposition;
	private Float stopposition;
	private Float longposition;
	private String reason;
	private Float closeposition;
	private String categoryname;
	
	public Integer getId( ) {
		return id;
	}

	public void setId( Integer id ) {
		this.id = id;
	}

	public String getUsertype( ) {
		return usertype;
	}

	public void setUsertype( String usertype ) {
		this.usertype = usertype;
	}

	public Integer getCategoryId( ) {
		return categoryId;
	}

	public void setCategoryId( Integer categoryId ) {
		this.categoryId = categoryId;
	}

	public Short getDirection( ) {
		return direction;
	}

	public void setDirection( Short direction ) {
		this.direction = direction;
	}

	public Float getOpenposition( ) {
		return openposition;
	}

	public void setOpenposition( Float openposition ) {
		this.openposition = openposition;
	}

	public Float getStopposition( ) {
		return stopposition;
	}

	public void setStopposition( Float stopposition ) {
		this.stopposition = stopposition;
	}

	public Float getLongposition( ) {
		return longposition;
	}

	public void setLongposition( Float longposition ) {
		this.longposition = longposition;
	}

	public String getReason( ) {
		return reason;
	}

	public void setReason( String reason ) {
		if( StringUtils.isNotBlank( reason ) ){
			reason = decode( reason );
		}
		this.reason = reason;
	}

	public Float getCloseposition( ) {
		return closeposition;
	}

	public void setCloseposition( Float closeposition ) {
		this.closeposition = closeposition;
	}

	public String getCategoryname( ) {
		return categoryname;
	}

	public void setCategoryname( String categoryname ) {
		if( StringUtils.isNotBlank( categoryname )){
			categoryname = decode( categoryname );
		}
		this.categoryname = categoryname;
	}

	private static final long serialVersionUID = 1L;

	private PostTask postTask;

	public PostTask getPostTask( ) {
		return postTask;
	}

	public void setPostTask( PostTask postTask ) {
		this.postTask = postTask;
	}
	
}
